"""First part is to import necessary modules"""

import os
"""Second part is to read the result of comparation"""
# initialize the score_board
score_board = {}
comp_num = 100 #how many comparation results we have
for i in range(1, comp_num):
# [how many times it loses, how many times it has been tested]
    score_board[str(i)] = [0,0]
 
comp_rds = open("compare.txt","r")
records = comp_rds.readlines()
for record in records:
    win = record[0]
    lose = record[1]
    score_board[lose][0] = score_board[lose][0] + 1
    score_board[win][1] = score_board[win][1] + 1
    score_board[lose][1] = score_board[lose][1] + 1

comp_rds.close()

"""Third part is to write final score into the file named compare.txt """
score = open("score.txt","a")
for i in range(1, comp_num):
    final_score = (1-score_board[str(i)][0]/score_board[str(i)][1])*100
    new_line = str(i) + " " + str(final_score) + "\n"
    score.write(new_line)
score.close()

import numpy as np
from scipy.sparse import csc_matrix


def pageRank(G, s=.85, maxerr=.0001):
    """
    Computes the pagerank for each of the n states
    Parameters
    ----------
    G: matrix representing state transitions
       Gij is a binary value representing a transition from state i to j.
    s: probability of following a transition. 1-s probability of teleporting
       to another state.
    maxerr: if the sum of pageranks between iterations is bellow this we will
            have converged.
    """
    n = G.shape[0]

    # transform G into markov matrix A
    A = csc_matrix(G, dtype=np.float)
    rsums = np.array(A.sum(1))[:, 0]
    ri, ci = A.nonzero()
    A.data /= rsums[ri]

    # bool array of sink states
    sink = rsums == 0

    # Compute pagerank r until we converge
    ro, r = np.zeros(n), np.ones(n)
    while np.sum(np.abs(r - ro)) > maxerr:
        ro = r.copy()
        # calculate each pagerank at a time
        for i in range(0, n):
            # inlinks of state i
            Ai = np.array(A[:, i].todense())[:, 0]
            # account for sink states
            Di = sink / float(n)
            # account for teleportation to state i
            Ei = np.ones(n) / float(n)

            r[i] = ro.dot(Ai * s + Di * s + Ei * (1 - s))

    # return normalized pagerank
    return r / float(sum(r))
